<?php

namespace Modules\Admin\Http\Controllers\ActivationCodes;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Modules\Common\General\Security\Api\Gateway;
use Modules\Common\Models\ActivationCodeUsage;
use Modules\Common\Models\ActivationCodeLogs;
use Modules\Common\Models\ActivationCodes;
use Modules\Common\Models\SubscriptionRecords;
use Modules\Common\Util\Api;
use Modules\Common\Util\Database;


class Update
{

    /**
     *@Route(path=/api/admin/activation-code  method=put)
    */
    public function index()
    {
        Api::validate(['id' => 'required|integer']);
        $id = request('id');
        $adminUserIdDefault = auth('api')->user()->id;
        $eidDefault = auth('api')->user()->eid; 
        $sidDefault = auth('api')->user()->sid;
        $activationCodes = ActivationCodes::updateFromArray([
            'id' => $id,
            'code'=>request('code'),
            'status'=>request('status'),
            'subscription_type_id'=>request('subscription_type_id'),
            'expire_time'=>request('expire_time'),
            'admin_user_id'=>$adminUserIdDefault,
            'eid'=>$eidDefault,
            'sid'=>$sidDefault,
        ]);
        return Api::success($activationCodes);
    }
    
    /**
     * @Route(path=/api/admin/batch-expire  method=put)
     */
    public function expire()
    {
        // 获取请求中的 ids 参数，并将其转换为数组
        $idsString = request('ids');
        if (empty($idsString)) {
            return Api::error('IDs are required.', 400);
        }
    
        // 使用 explode 函数将字符串转换为数组
        $ids = explode(',', $idsString);
        $ids = array_filter($ids, function ($id) {
            return is_numeric($id) && $id > 0;
        });
    
        if (empty($ids)) {
            return Api::error('Invalid IDs provided.', 400);
        }
    
        // 执行更新操作
        DB::beginTransaction();
        try {
            $adminUserIdDefault = auth('api')->user()->id;
            $eidDefault = auth('api')->user()->eid; 
            $sidDefault = auth('api')->user()->sid;
    
            // 更新激活码状态
            $updateCount = ActivationCodes::whereIn('id', $ids)
                ->update([
                    'updated_at' => now(),
                    'status' => 3,
                    'admin_user_id' => $adminUserIdDefault,
                    'eid' => $eidDefault,
                    'sid' => $sidDefault
                ]);
    
            if ($updateCount > 0) {
                // 更新成功
                DB::commit();
                return Api::success();
            } else {
                // 没有找到要更新的激活码
                return Api::fail('没有找到要更新的激活码', 404);
            }
        } catch (Exception $e) {
            DB::rollBack();
            return Api::fail($e->getMessage(), 500);
        }
    }
}